<?php 
//defined('C5_EXECUTE') or die("Access Denied.");


class MultiLanguage {
	
	// Define default language.
	public  static $defaultLanguage = 'fr';

	// Define all available languages.
	public  static $userAcceptLanguage = array(
		'fr',
		'en'
	);
	
	public static function setUserSelectedLanguage($UserSelectedLanguage) {
		$cookieLength = time() + (60*24*60*60);
		setcookie('UserSelectedLanguage', $UserSelectedLanguage, $cookieLength);
	}
	
	public static function getUserSelectedLanguage() {
		
		$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
		
		if (strpos($url, '/fr/') !== false) {
			MultiLanguage::setUserSelectedLanguage('fr');
			return 'fr';
		} else if (strpos($url, '/en/') !== false) {
			MultiLanguage::setUserSelectedLanguage('en');
			return 'en';
		}
		
		if (isset($_COOKIE['UserSelectedLanguage'])) {
			$UserSelectedLanguage = $_COOKIE['UserSelectedLanguage'];
		} else {
			$UserSelectedLanguage = MultiLanguage::getUserDefaultLanguage();
		}
		MultiLanguage::setUserSelectedLanguage($UserSelectedLanguage);
		
		return $UserSelectedLanguage;
	}
	
	
	 static function lang_initglobal($Var) {
	 	
		if(empty($GLOBALS[$Var])) {
			$GLOBALS[$Var]=(!empty($GLOBALS['_SERVER'][$Var]))? 
			    $GLOBALS['_SERVER'][$Var]: 
			    (!empty($GLOBALS['HTTP_SERVER_VARS'][$Var]))? 
			          $GLOBALS['HTTP_SERVER_VARS'][$Var]:
			          '';
		}
	}
	
	 static function getUserDefaultLanguage() {
		// Detect HTTP_ACCEPT_LANGUAGE & HTTP_USER_AGENT.
		MultiLanguage::lang_initglobal('HTTP_ACCEPT_LANGUAGE');
		MultiLanguage::lang_initglobal('HTTP_USER_AGENT');
	
		$_AL=strtolower($GLOBALS['HTTP_ACCEPT_LANGUAGE']);
		$_UA=strtolower($GLOBALS['HTTP_USER_AGENT']);
	
		// Try to detect Primary language if several languages are accepted.
		foreach(MultiLanguage::$userAcceptLanguage as $K) {
			if(strpos($_AL, $K)===0)
			return $K;
		}
	
		// Try to detect any language if not yet detected.
		foreach(MultiLanguage::$userAcceptLanguage as $K) {
			if(strpos($_AL, $K)!==false)
			return $K;
		}
		
		foreach(MultiLanguage::$userAcceptLanguage as $K) {
			if(preg_match("/[\[\( ]{$K}[;,_\-\)]/",$_UA))
			return $K;
		}
	
		// Return default language if language is not yet detected.
		return MultiLanguage::$defaultLanguage;
	}
}

